import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { getClientIp } from 'request-ip';
import { Request, Response } from 'express';
import { QueryFailedError } from 'typeorm';

@Catch()
export class AllExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger();

  constructor(private readonly httpAdapterHost: HttpAdapterHost) {}

  catch(exception: any, host: ArgumentsHost) {
    const { httpAdapter } = this.httpAdapterHost;
    const ctx = host.switchToHttp();
    const request = ctx.getRequest<Request>();
    const response = ctx.getResponse<Response>();

    const httpStatus =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    console.log('exception', exception);
    let msg: unknown =
      exception.response || exception.sqlMessage || 'Internal server error';

    // 加入更多异常错误逻辑 sql 查询出错
    if (exception instanceof QueryFailedError) {
      msg = exception.message;
    }

    const responseBody = {
      headers: request.headers,
      query: request.query,
      body: request.body as unknown,
      params: request.params,
      timestamp: new Date().toISOString(),
      ip: getClientIp(request),
      exception: exception.name,
      error: msg,
    };

    this.logger.error('[toimc]', responseBody);
    httpAdapter.reply(response, responseBody, httpStatus);
  }
}
